package api06;

public class SyncDemo {
    private static boolean flag1 = false;
    private static boolean flag2 = false;

    public static void main(String[] args) {
        Bank bank = new Bank();
        int i = 0;
        while (true) {

            Thread t1 = new Thread(){
                public void run(){
                    flag1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread(){
                public void run(){
                    flag2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
            }
            if(flag1&&flag2){
                System.out.println("成功");
                break;
            }else{
                System.out.println("失败");
                flag1 = false;
                flag2 = false;
                bank.saveBalance(20000);
            }
            i++;
        }
        System.out.println(i);
    }
}

class Bank{

    private int balance = 20000;

    public boolean getMoney(int money){
        int balance = getBalance();
        if (balance>=money) {
            balance-=money;
            Thread.yield();
            saveBalance(balance);
            return true;
        }return false;
    }
    public void saveBalance(int balance){
        this.balance = balance;
    }


    public int getBalance() {
        return balance;
    }
}